package com.waitingresult.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: WangShuai
 * @CreateTime: 2022-11-01  08:36
 * @Description:
 * @Version: 1.0
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws Exception {
        final int totalThread = 10000;
        //CountDownLatch 条件=10
        AtomicInteger a = new AtomicInteger();
        CountDownLatch countDownLatch = new CountDownLatch(totalThread);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < totalThread; i++) {
            executorService.execute(() -> {
                System.out.println("run..");
                // countDownLatch每次减减
                a.addAndGet(1);
                countDownLatch.countDown();
            });
        }
        // 必须到0 才会放行，  不然就会死锁
        countDownLatch.await();
        System.out.println(a);
        System.out.println(a);
        executorService.shutdown();
    }
}
